<template>
  <div class="tutorial-management">
    <!-- 顶部统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon tutorial">
          <i class="el-icon-document"></i>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ stats.totalCount || 0 }}</div>
          <div class="stat-label">教程总数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon published">
          <i class="el-icon-check"></i>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ stats.publishedCount || 0 }}</div>
          <div class="stat-label">已发布</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon draft">
          <i class="el-icon-edit"></i>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ stats.draftCount || 0 }}</div>
          <div class="stat-label">草稿</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon steps">
          <i class="el-icon-menu"></i>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ stats.totalSteps || 0 }}</div>
          <div class="stat-label">总步骤数</div>
        </div>
      </div>
    </div>

    <!-- 快速筛选区域 -->
    <div class="quick-filter-section">
      <div class="filter-tabs">
        <el-button
          :type="searchForm.category === null ? 'primary' : ''"
          @click="quickFilter(null)"
        >
          全部教程
        </el-button>
        <el-button
          :type="searchForm.category === 1 ? 'primary' : ''"
          @click="quickFilter(1)"
        >
          基础入门
        </el-button>
        <el-button
          :type="searchForm.category === 2 ? 'primary' : ''"
          @click="quickFilter(2)"
        >
          进阶技法
        </el-button>
        <el-button
          :type="searchForm.category === 3 ? 'primary' : ''"
          @click="quickFilter(3)"
        >
          高级创作
        </el-button>
      </div>
    </div>

    <!-- 搜索和操作栏 -->
    <div class="toolbar">
      <div class="search-section">
        <el-input
          v-model="searchForm.title"
          placeholder="搜索教程标题"
          prefix-icon="el-icon-search"
          clearable
          @keyup.enter="searchTutorials"
        />
        <el-select v-model="searchForm.category" placeholder="选择分类" clearable>
          <el-option label="基础入门" :value="1" />
          <el-option label="进阶技法" :value="2" />
          <el-option label="高级创作" :value="3" />
        </el-select>
        <el-select v-model="searchForm.difficultyLevel" placeholder="选择难度" clearable>
          <el-option label="初级" :value="1" />
          <el-option label="中级" :value="2" />
          <el-option label="高级" :value="3" />
        </el-select>
        <el-select v-model="searchForm.status" placeholder="发布状态" clearable>
          <el-option label="草稿" :value="0" />
          <el-option label="已发布" :value="1" />
          <el-option label="已下架" :value="2" />
        </el-select>
        <el-button type="primary" icon="el-icon-search" @click="searchTutorials">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetSearch">重置</el-button>
      </div>
      <div class="action-section">
        <el-button type="primary" icon="el-icon-plus" @click="openTutorialForm">新增教程</el-button>
        <el-button
          type="danger"
          icon="el-icon-delete"
          :disabled="selectedTutorials.length === 0"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 教程列表 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="tutorials"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column label="封面图" width="100" align="center">
          <template #default="{ row }">
            <el-image
              :src="getImageUrl(row.coverImage) || '/images/tutorial/default.png'"
              :preview-src-list="[getImageUrl(row.coverImage)]"
              fit="cover"
              class="cover-image"
            />
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="categoryText" label="分类" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getCategoryType(row.category)">{{ row.categoryText }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="difficultyLevelText" label="难度" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getDifficultyType(row.difficultyLevel)">{{ row.difficultyLevelText }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="estimatedTime" label="预计时长" width="120" align="center">
          <template #default="scope">
            {{ scope.row.estimatedTime ? scope.row.estimatedTime + '分钟' : '暂无' }}
          </template>
        </el-table-column>
        <el-table-column prop="stepsCount" label="步骤数" width="100" align="center">
          <template #default="{ row }">
            <span class="steps-count">{{ row.stepsCount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="isRecommend" label="推荐" width="80" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.isRecommend" type="success" size="small">推荐</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="viewCount" label="浏览量" width="100" align="center">
          <template #default="{ row }">
            <span class="view-count">{{ row.viewCount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center" />
        <el-table-column label="操作" width="260" align="center" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button size="small" type="primary" @click="viewTutorial(row)">查看</el-button>
              <el-button size="small" type="warning" @click="editTutorial(row)">编辑</el-button>
              <el-button size="small" type="info" @click="manageSteps(row)">步骤</el-button>
              <el-button size="small" type="danger" @click="deleteTutorial(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <div class="pagination-info">
        共 {{ pagination.total }} 条数据
      </div>
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        :pager-count="5"
        :disabled="loading"
        layout="sizes, prev, pager, next"
        class="custom-pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 教程表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入教程标题" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="副标题">
              <el-input v-model="form.subtitle" placeholder="请输入副标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-select v-model="form.category" placeholder="选择分类">
                <el-option label="基础入门" :value="1" />
                <el-option label="进阶技法" :value="2" />
                <el-option label="高级创作" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="难度级别" prop="difficultyLevel">
              <el-select v-model="form.difficultyLevel" placeholder="选择难度">
                <el-option label="初级" :value="1" />
                <el-option label="中级" :value="2" />
                <el-option label="高级" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="封面图">
              <div class="upload-container">
                <el-upload
                  class="cover-uploader"
                  action="#"
                  :http-request="handleImageUpload"
                  :show-file-list="false"
                  :before-upload="beforeCoverUpload"
                  accept="image/*"
                >
                  <img v-if="form.coverImage" :src="getImageUrl(form.coverImage)" class="cover-image" />
                  <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <div class="upload-tip">
                  支持 jpg、png、gif 格式，文件大小不超过 10MB
                </div>
                <div v-if="form.coverImage" class="image-actions">
                  <el-button size="small" type="danger" @click="handleRemoveCoverImage">删除图片</el-button>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="简介">
              <el-input
                v-model="form.summary"
                type="textarea"
                :rows="3"
                placeholder="请输入教程简介"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细内容">
              <el-input
                v-model="form.content"
                type="textarea"
                :rows="6"
                placeholder="请输入详细内容"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计时长">
              <el-input-number v-model="form.estimatedTime" :min="0" placeholder="分钟" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="视频时长">
              <el-input-number v-model="form.videoDuration" :min="0" placeholder="秒" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所需工具">
              <el-input v-model="form.toolsRequired" placeholder="请输入所需工具" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所需材料">
              <el-input v-model="form.materialsRequired" placeholder="请输入所需材料" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="教程视频">
              <div class="upload-container">
                <el-upload
                  class="video-uploader"
                  action="#"
                  :http-request="handleTutorialVideoUpload"
                  :show-file-list="false"
                  :before-upload="beforeTutorialVideoUpload"
                  accept="video/*"
                >
                  <div v-if="form.videoUrl" class="video-preview-container">
                    <video
                      :src="getVideoUrl(form.videoUrl)"
                      class="video-preview"
                      preload="metadata"
                    >
                      您的浏览器不支持视频播放
                    </video>
                    <div class="video-overlay">
                      <el-icon class="video-play-icon"><VideoPlay /></el-icon>
                      <span class="video-overlay-text">点击重新上传</span>
                    </div>
                  </div>
                  <div v-else class="video-upload-placeholder">
                    <el-icon class="video-uploader-icon"><VideoCamera /></el-icon>
                  </div>
                </el-upload>
                <div class="upload-tip">
                  支持 MP4、AVI、MOV、MKV 等格式，大小 ≤ 500MB
                </div>
                <div v-if="form.videoUrl" class="video-actions">
                  <div class="video-filename">
                    <span>{{ form.videoFilename || '已上传视频文件' }}</span>
                  </div>
                  <el-button size="small" type="danger" @click="handleRemoveTutorialVideo">删除视频</el-button>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="标签">
              <el-input v-model="form.tags" placeholder="多个标签用逗号分隔" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序号">
              <el-input-number v-model="form.sortOrder" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否推荐">
              <el-switch v-model="form.isRecommend" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否免费">
              <el-switch v-model="form.isFree" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio :label="0">草稿</el-radio>
                <el-radio :label="1">发布</el-radio>
                <el-radio :label="2">下架</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveTutorial" :loading="saving">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看教程详情弹窗 -->
    <el-dialog v-model="viewDialogVisible" title="教程详情" width="800px">
      <div class="view-content" v-if="viewData">
        <div class="section">
          <h3 class="section-title">基本信息</h3>
          <div class="info-grid">
            <div class="info-item">
              <label>标题：</label>
              <span>{{ viewData.title || '暂无' }}</span>
            </div>
            <div class="info-item">
              <label>副标题：</label>
              <span>{{ viewData.subtitle || '暂无' }}</span>
            </div>
            <div class="info-item">
              <label>分类：</label>
              <span>{{ viewData.categoryText || '暂无' }}</span>
            </div>
            <div class="info-item">
              <label>难度级别：</label>
              <span>{{ viewData.difficultyLevelText || '暂无' }}</span>
            </div>
            <div class="info-item">
              <label>状态：</label>
              <el-tag :type="getStatusType(viewData.status)">{{ viewData.statusText || '暂无' }}</el-tag>
            </div>
            <div class="info-item">
              <label>预计时长：</label>
              <span>{{ viewData.estimatedTime ? viewData.estimatedTime + '分钟' : '暂无' }}</span>
            </div>
          </div>
        </div>

        <div class="section" v-if="viewData.coverImage">
          <h3 class="section-title">封面图片</h3>
          <div class="cover-preview">
            <img :src="getImageUrl(viewData.coverImage)" alt="封面图片" class="preview-image" />
          </div>
        </div>

        <div class="section">
          <h3 class="section-title">内容信息</h3>
          <div class="content-info">
            <div class="info-item">
              <label>简介：</label>
              <p>{{ viewData.summary || '暂无' }}</p>
            </div>
            <div class="info-item">
              <label>详细内容：</label>
              <div v-html="viewData.content || '暂无'" class="content-html"></div>
            </div>
          </div>
        </div>

        <div class="section">
          <h3 class="section-title">教程信息</h3>
          <div class="info-grid">
            <div class="info-item">
              <label>所需工具：</label>
              <span>{{ viewData.toolsRequired || '暂无' }}</span>
            </div>
            <div class="info-item">
              <label>所需材料：</label>
              <span>{{ viewData.materialsRequired || '暂无' }}</span>
            </div>
            <div class="info-item">
              <label>步骤数量：</label>
              <span>{{ viewData.stepsCount || 0 }}</span>
            </div>
            <div class="info-item">
              <label>视频地址：</label>
              <span>{{ viewData.videoUrl || '暂无' }}</span>
            </div>
            <div class="info-item">
              <label>视频时长：</label>
              <span>{{ viewData.videoDuration ? viewData.videoDuration + '秒' : '暂无' }}</span>
            </div>
            <div class="info-item">
              <label>标签：</label>
              <span>{{ viewData.tags || '暂无' }}</span>
            </div>
          </div>
        </div>

        <div class="section">
          <h3 class="section-title">统计信息</h3>
          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-value">{{ viewData.viewCount || 0 }}</div>
              <div class="stat-label">浏览量</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ viewData.likeCount || 0 }}</div>
              <div class="stat-label">点赞数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ viewData.favoriteCount || 0 }}</div>
              <div class="stat-label">收藏数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ viewData.studyCount || 0 }}</div>
              <div class="stat-label">学习数</div>
            </div>
          </div>
        </div>

        <div class="section">
          <h3 class="section-title">其他信息</h3>
          <div class="info-grid">
            <div class="info-item">
              <label>是否推荐：</label>
              <el-tag v-if="viewData.isRecommend" type="success" size="small">推荐</el-tag>
              <span v-else>否</span>
            </div>
            <div class="info-item">
              <label>是否免费：</label>
              <el-tag v-if="viewData.isFree" type="success" size="small">免费</el-tag>
              <span v-else>付费</span>
            </div>
            <div class="info-item">
              <label>排序号：</label>
              <span>{{ viewData.sortOrder || 0 }}</span>
            </div>
            <div class="info-item">
              <label>创建时间：</label>
              <span>{{ viewData.createTime || '暂无' }}</span>
            </div>
            <div class="info-item">
              <label>更新时间：</label>
              <span>{{ viewData.updateTime || '暂无' }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 步骤管理弹窗 -->
    <el-dialog v-model="stepsDialogVisible" title="步骤管理" width="1000px" :close-on-click-modal="false">
      <div class="steps-management">
        <div class="steps-header">
          <h4>{{ currentTutorialForSteps?.title }} - 步骤列表</h4>
          <el-button type="primary" @click="addStep">添加步骤</el-button>
        </div>

        <el-table :data="steps" v-loading="stepsLoading" style="width: 100%">
          <el-table-column prop="stepNumber" label="步骤号" width="80" />
          <el-table-column prop="title" label="步骤标题" min-width="200" show-overflow-tooltip />
          <el-table-column label="步骤图片" width="100">
            <template #default="scope">
              <img v-if="scope.row.imageUrl" :src="getImageUrl(scope.row.imageUrl)" class="step-image" />
              <span v-else>暂无图片</span>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
          <el-table-column prop="tips" label="提示" min-width="150" show-overflow-tooltip />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="editStep(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="deleteStep(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 步骤编辑弹窗 -->
    <el-dialog
      v-model="stepDialogVisible"
      :title="stepDialogTitle"
      width="800px"
      destroy-on-close
    >
      <el-form
        ref="stepFormRef"
        :model="stepForm"
        :rules="stepRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="步骤标题" prop="title">
              <el-input v-model="stepForm.title" placeholder="请输入步骤标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="步骤编号" prop="stepNumber">
              <el-input-number v-model="stepForm.stepNumber" :min="1" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序号">
              <el-input-number v-model="stepForm.sortOrder" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="步骤图片">
              <div class="upload-container">
                <el-upload
                  class="cover-uploader"
                  action="#"
                  :http-request="handleStepImageUpload"
                  :show-file-list="false"
                  :before-upload="beforeStepImageUpload"
                  accept="image/*"
                >
                  <img v-if="stepForm.imageUrl" :src="getImageUrl(stepForm.imageUrl)" class="cover-image" />
                  <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <div class="upload-tip">
                  支持 jpg、png、gif 格式，文件大小不超过 10MB
                </div>
                <div v-if="stepForm.imageUrl" class="image-actions">
                  <el-button size="small" type="danger" @click="handleRemoveStepImage">删除图片</el-button>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="教学视频">
              <div class="upload-container">
                <el-upload
                  class="video-uploader"
                  action="#"
                  :http-request="handleStepVideoUpload"
                  :show-file-list="false"
                  :before-upload="beforeStepVideoUpload"
                  accept="video/*"
                >
                  <div v-if="stepForm.videoUrl" class="video-preview">
                    <video
                      :src="getVideoUrl(stepForm.videoUrl)"
                      controls
                      class="preview-video"
                      preload="metadata"
                    >
                      您的浏览器不支持视频播放
                    </video>
                    <div class="video-overlay">
                      <el-icon class="video-icon"><VideoPlay /></el-icon>
                      <span class="video-text">点击重新上传</span>
                    </div>
                  </div>
                  <div v-else class="video-upload-area">
                    <el-icon class="video-upload-icon"><VideoCamera /></el-icon>
                    <div class="upload-text">
                      <p>点击上传教学视频</p>
                      <p class="upload-hint">支持 MP4、AVI、MOV 等格式</p>
                    </div>
                  </div>
                </el-upload>
                <div class="upload-tip">
                  支持 MP4、AVI、MOV、WMV、FLV、WEBM 格式，文件大小不超过 100MB
                </div>
                <div v-if="stepForm.videoUrl" class="video-actions">
                  <el-button size="small" type="danger" @click="handleRemoveStepVideo">删除视频</el-button>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="stepForm.videoUrl">
            <el-form-item label="视频时长">
              <el-input-number v-model="stepForm.videoDuration" :min="0" placeholder="秒" style="width: 100%" />
              <span style="margin-left: 8px; color: #909399; font-size: 12px;">可选，单位：秒</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="步骤描述">
              <el-input
                v-model="stepForm.description"
                type="textarea"
                :rows="4"
                placeholder="请输入步骤描述"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="操作提示">
              <el-input
                v-model="stepForm.tips"
                type="textarea"
                :rows="3"
                placeholder="请输入操作提示"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="stepDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveStep" :loading="stepSaving">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, VideoCamera, VideoPlay } from '@element-plus/icons-vue'
import { getTutorialPage, getTutorialDetail, createTutorial, updateTutorial, deleteTutorial as deleteTutorialApi } from '@/api/tutorial'
import { getTutorialSteps, createTutorialStep, updateTutorialStep, deleteTutorialStep } from '@/api/tutorial-step'
import { uploadImage, deleteImage, uploadVideo, deleteVideo } from '@/api/upload'
import { getImageUrl, getVideoUrl, handleImageError } from '@/utils/imageUtils'

export default {
  name: 'TutorialManagement',
  components: {
    Plus,
    VideoCamera,
    VideoPlay
  },
  setup() {
    // 数据状态
    const loading = ref(false)
    const saving = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('新增教程')
    const formRef = ref(null)

    // 查看弹窗
    const viewDialogVisible = ref(false)
    const viewData = ref({})

    // 步骤管理
    const stepsDialogVisible = ref(false)
    const stepsLoading = ref(false)
    const currentTutorialForSteps = ref(null)
    const steps = ref([])

    // 步骤编辑
    const stepDialogVisible = ref(false)
    const stepDialogTitle = ref('添加步骤')
    const stepSaving = ref(false)
    const stepFormRef = ref(null)

    // 搜索表单
    const searchForm = reactive({
      title: '',
      category: null,
      difficultyLevel: null,
      status: null
    })

    // 教程列表
    const tutorials = ref([])
    const selectedTutorials = ref([])

    // 统计数据
    const stats = reactive({
      totalCount: 0,
      publishedCount: 0,
      draftCount: 0,
      totalSteps: 0
    })

    // 分页信息
    const pagination = reactive({
      page: 1,
      size: 10,
      total: 0
    })

    // 教程表单
    const form = reactive({
      id: null,
      title: '',
      subtitle: '',
      coverImage: '',
      summary: '',
      content: '',
      videoUrl: '',
      videoFilename: '',
      videoDuration: null,
      difficultyLevel: 1,
      category: 1,
      tags: '',
      toolsRequired: '',
      materialsRequired: '',
      estimatedTime: null,
      sortOrder: 0,
      status: 0,
      isRecommend: false,
      isFree: true
    })

    // 表单验证规则
    const rules = {
      title: [
        { required: true, message: '请输入教程标题', trigger: 'blur' },
        { min: 1, max: 200, message: '标题长度在 1 到 200 个字符', trigger: 'blur' }
      ],
      category: [
        { required: true, message: '请选择分类', trigger: 'change' }
      ],
      difficultyLevel: [
        { required: true, message: '请选择难度级别', trigger: 'change' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    }

    // 步骤表单
    const stepForm = reactive({
      id: null,
      tutorialId: null,
      stepNumber: 1,
      title: '',
      description: '',
      imageUrl: '',
      videoUrl: '',
      videoDuration: null, // 视频时长(秒)
      tips: '',
      sortOrder: 0
    })

    // 步骤表单验证规则
    const stepRules = {
      stepNumber: [
        { required: true, message: '请输入步骤编号', trigger: 'blur' }
      ],
      title: [
        { required: true, message: '请输入步骤标题', trigger: 'blur' },
        { min: 1, max: 200, message: '标题长度在 1 到 200 个字符', trigger: 'blur' }
      ]
    }
    
    // 获取教程列表
    const fetchTutorials = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.page, // 后端分页从1开始
          size: pagination.size,
          ...searchForm
        }
        const response = await getTutorialPage(params)
        if (response.code === 200) {
          tutorials.value = response.data.records || []
          pagination.total = response.data.total || 0

          // 计算统计数据
          await loadStats()
        } else {
          ElMessage.error(response.message || '获取教程列表失败')
        }
      } catch (error) {
        console.error('获取教程列表失败:', error)
        ElMessage.error('获取教程列表失败')
      } finally {
        loading.value = false
      }
    }

    // 加载统计信息
    const loadStats = async () => {
      try {
        // 获取所有教程数据用于统计
        const allParams = { page: 1, size: 1000 }
        const response = await getTutorialPage(allParams)
        if (response.code === 200) {
          const allTutorials = response.data.records || []
          stats.totalCount = allTutorials.length
          stats.publishedCount = allTutorials.filter(t => t.status === 1).length
          stats.draftCount = allTutorials.filter(t => t.status === 0).length
          stats.totalSteps = allTutorials.reduce((sum, t) => sum + (t.stepsCount || 0), 0)
        }
      } catch (error) {
        console.error('加载统计信息失败:', error)
      }
    }

    // 搜索教程
    const searchTutorials = () => {
      pagination.page = 1
      fetchTutorials()
    }

    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchForm, {
        title: '',
        category: null,
        difficultyLevel: null,
        status: null
      })
      searchTutorials()
    }

    // 快速筛选
    const quickFilter = (category) => {
      searchForm.category = category
      searchTutorials()
    }

    // 刷新数据
    const refreshData = () => {
      fetchTutorials()
    }

    // 打开教程表单
    const openTutorialForm = () => {
      dialogTitle.value = '新增教程'
      resetForm()
      dialogVisible.value = true
    }

    // 重置表单
    const resetForm = () => {
      Object.assign(form, {
        id: null,
        title: '',
        subtitle: '',
        coverImage: '',
        summary: '',
        content: '',
        videoUrl: '',
        videoFilename: '',
        videoDuration: null,
        difficultyLevel: 1,
        category: 1,
        tags: '',
        toolsRequired: '',
        materialsRequired: '',
        estimatedTime: null,
        sortOrder: 0,
        status: 0,
        isRecommend: false,
        isFree: true
      })
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    }

    // 编辑教程
    const editTutorial = async (row) => {
      try {
        const response = await getTutorialDetail(row.id)
        if (response.code === 200) {
          dialogTitle.value = '编辑教程'
          Object.assign(form, response.data.tutorial)
          dialogVisible.value = true
        } else {
          ElMessage.error(response.message || '获取教程详情失败')
        }
      } catch (error) {
        console.error('获取教程详情失败:', error)
        ElMessage.error('获取教程详情失败')
      }
    }
    
    // 保存教程
    const saveTutorial = async () => {
      if (!formRef.value) return

      try {
        await formRef.value.validate()
        saving.value = true

        if (form.id) {
          // 更新操作
          const response = await updateTutorial(form)
          if (response.code === 200) {
            ElMessage.success('更新成功')
            dialogVisible.value = false
            fetchTutorials()
          } else {
            ElMessage.error(response.message || '更新失败')
          }
        } else {
          // 新增操作
          const response = await createTutorial(form)
          if (response.code === 200) {
            ElMessage.success('创建成功')
            dialogVisible.value = false
            fetchTutorials()
          } else {
            ElMessage.error(response.message || '创建失败')
          }
        }
      } catch (error) {
        console.error('保存教程失败:', error)
        ElMessage.error('保存失败')
      } finally {
        saving.value = false
      }
    }

    // 删除教程
    const deleteTutorial = (row) => {
      ElMessageBox.confirm(
        `确定要删除"${row.title}"吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          const response = await deleteTutorialApi(row.id)
          if (response.code === 200) {
            ElMessage.success('删除成功')
            fetchTutorials()
          } else {
            ElMessage.error(response.message || '删除失败')
          }
        } catch (error) {
          console.error('删除教程失败:', error)
          ElMessage.error('删除失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }

    // 查看教程
    const viewTutorial = async (row) => {
      try {
        const response = await getTutorialDetail(row.id)
        if (response.code === 200) {
          viewData.value = response.data.tutorial
          viewDialogVisible.value = true
        } else {
          ElMessage.error(response.message || '获取详情失败')
        }
      } catch (error) {
        console.error('获取教程详情失败:', error)
        ElMessage.error('获取详情失败')
      }
    }



    // 上传前检查
    const beforeCoverUpload = (file) => {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isJPG) {
        ElMessage.error('只能上传 JPG、PNG、GIF 格式的图片!')
        return false
      }
      if (!isLt10M) {
        ElMessage.error('图片大小不能超过 10MB!')
        return false
      }
      return true
    }

    // 自定义上传
    const handleImageUpload = async (options) => {
      const { file } = options

      try {
        const response = await uploadImage(file)
        if (response.code === 200) {
          form.coverImage = response.data.url
          ElMessage.success('图片上传成功')
        } else {
          ElMessage.error(response.message || '上传失败')
        }
      } catch (error) {
        console.error('上传失败:', error)
        ElMessage.error('上传失败')
      }
    }

    // 删除封面图片
    const handleRemoveCoverImage = async () => {
      if (form.coverImage) {
        try {
          await deleteImage(form.coverImage)
          form.coverImage = ''
          ElMessage.success('图片删除成功')
        } catch (error) {
          console.error('删除失败:', error)
          ElMessage.warning('图片删除失败，但已从表单中移除')
          form.coverImage = ''
        }
      }
    }
    
    // 步骤管理
    const manageSteps = async (row) => {
      currentTutorialForSteps.value = row
      stepsDialogVisible.value = true
      await fetchSteps(row.id)
    }

    // 获取步骤列表
    const fetchSteps = async (tutorialId) => {
      stepsLoading.value = true
      try {
        const response = await getTutorialSteps(tutorialId)
        if (response.code === 200) {
          steps.value = response.data || []
        } else {
          ElMessage.error(response.message || '获取步骤列表失败')
        }
      } catch (error) {
        console.error('获取步骤列表失败:', error)
        ElMessage.error('获取步骤列表失败')
      } finally {
        stepsLoading.value = false
      }
    }

    // 添加步骤
    const addStep = () => {
      stepDialogTitle.value = '添加步骤'
      resetStepForm()
      stepForm.tutorialId = currentTutorialForSteps.value.id
      stepForm.stepNumber = steps.value.length + 1
      stepDialogVisible.value = true
    }

    // 编辑步骤
    const editStep = (row) => {
      stepDialogTitle.value = '编辑步骤'
      Object.assign(stepForm, row)
      stepDialogVisible.value = true
    }

    // 重置步骤表单
    const resetStepForm = () => {
      Object.assign(stepForm, {
        id: null,
        tutorialId: null,
        stepNumber: 1,
        title: '',
        description: '',
        imageUrl: '',
        videoUrl: '',
        videoDuration: null,
        tips: '',
        sortOrder: 0
      })
      if (stepFormRef.value) {
        stepFormRef.value.clearValidate()
      }
    }

    // 保存步骤
    const saveStep = async () => {
      if (!stepFormRef.value) return

      try {
        await stepFormRef.value.validate()
        stepSaving.value = true

        if (stepForm.id) {
          // 更新操作
          const response = await updateTutorialStep(stepForm)
          if (response.code === 200) {
            ElMessage.success('更新成功')
            stepDialogVisible.value = false
            await fetchSteps(currentTutorialForSteps.value.id)
          } else {
            ElMessage.error(response.message || '更新失败')
          }
        } else {
          // 新增操作
          const response = await createTutorialStep(stepForm)
          if (response.code === 200) {
            ElMessage.success('创建成功')
            stepDialogVisible.value = false
            await fetchSteps(currentTutorialForSteps.value.id)
          } else {
            ElMessage.error(response.message || '创建失败')
          }
        }
      } catch (error) {
        console.error('保存步骤失败:', error)
        ElMessage.error('保存失败')
      } finally {
        stepSaving.value = false
      }
    }

    // 删除步骤
    const deleteStep = (row) => {
      ElMessageBox.confirm(
        `确定要删除步骤"${row.title}"吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          const response = await deleteTutorialStep(row.id)
          if (response.code === 200) {
            ElMessage.success('删除成功')
            await fetchSteps(currentTutorialForSteps.value.id)
          } else {
            ElMessage.error(response.message || '删除失败')
          }
        } catch (error) {
          console.error('删除步骤失败:', error)
          ElMessage.error('删除失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }

    // 步骤图片自定义上传
    const handleStepImageUpload = async (options) => {
      const { file } = options

      try {
        const response = await uploadImage(file)
        if (response.code === 200) {
          stepForm.imageUrl = response.data.url
          ElMessage.success('图片上传成功')
        } else {
          ElMessage.error(response.message || '上传失败')
        }
      } catch (error) {
        console.error('上传失败:', error)
        ElMessage.error('上传失败')
      }
    }

    // 删除步骤图片
    const handleRemoveStepImage = async () => {
      if (stepForm.imageUrl) {
        try {
          await deleteImage(stepForm.imageUrl)
          stepForm.imageUrl = ''
          ElMessage.success('图片删除成功')
        } catch (error) {
          console.error('删除失败:', error)
          ElMessage.warning('图片删除失败，但已从表单中移除')
          stepForm.imageUrl = ''
        }
      }
    }

    // 步骤图片上传成功处理（保留兼容性）
    const handleStepImageSuccess = (response) => {
      if (response.code === 200) {
        stepForm.imageUrl = response.data.url
        ElMessage.success('上传成功')
      } else {
        ElMessage.error(response.message || '上传失败')
      }
    }

    // 步骤图片上传前检查
    const beforeStepImageUpload = (file) => {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isJPG) {
        ElMessage.error('只能上传 JPG、PNG、GIF 格式的图片!')
        return false
      }
      if (!isLt10M) {
        ElMessage.error('图片大小不能超过 10MB!')
        return false
      }
      return true
    }

    // 步骤视频自定义上传
    const handleStepVideoUpload = async (options) => {
      const { file } = options

      try {
        const response = await uploadVideo(file)
        if (response.code === 200) {
          stepForm.videoUrl = response.data.url
          ElMessage.success('视频上传成功')
        } else {
          ElMessage.error(response.message || '视频上传失败')
        }
      } catch (error) {
        console.error('视频上传失败:', error)
        ElMessage.error('视频上传失败')
      }
    }

    // 步骤视频上传前检查
    const beforeStepVideoUpload = (file) => {
      const allowedTypes = ['video/mp4', 'video/avi', 'video/mov', 'video/wmv', 'video/flv', 'video/webm']
      const isVideo = allowedTypes.includes(file.type)
      const isLt100M = file.size / 1024 / 1024 < 100

      if (!isVideo) {
        ElMessage.error('只能上传 MP4、AVI、MOV、WMV、FLV、WEBM 格式的视频!')
        return false
      }
      if (!isLt100M) {
        ElMessage.error('视频大小不能超过 100MB!')
        return false
      }
      return true
    }

    // 删除步骤视频
    const handleRemoveStepVideo = async () => {
      if (stepForm.videoUrl) {
        try {
          await deleteVideo(stepForm.videoUrl)
          stepForm.videoUrl = ''
          ElMessage.success('视频删除成功')
        } catch (error) {
          console.error('删除失败:', error)
          ElMessage.warning('视频删除失败，但已从表单中移除')
          stepForm.videoUrl = ''
        }
      }
    }

    // 教程视频自定义上传
    const handleTutorialVideoUpload = async (options) => {
      const { file } = options

      try {
        const response = await uploadVideo(file)
        if (response.code === 200) {
          form.videoUrl = response.data.url
          form.videoFilename = response.data.originalFilename
          ElMessage.success('视频上传成功')
        } else {
          ElMessage.error(response.message || '视频上传失败')
        }
      } catch (error) {
        console.error('视频上传失败:', error)
        ElMessage.error('视频上传失败')
      }
    }

    // 教程视频上传前检查
    const beforeTutorialVideoUpload = (file) => {
      // 支持的视频格式
      const allowedTypes = [
        'video/mp4', 'video/avi', 'video/mov', 'video/wmv', 
        'video/flv', 'video/webm', 'video/mkv', 'video/3gp',
        'video/mp4v', 'video/x-msvideo', 'video/quicktime'
      ]
      
      // 通过文件扩展名也进行检查
      const fileName = file.name.toLowerCase()
      const allowedExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv', '3gp']
      const fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1)
      
      const isVideoByType = allowedTypes.includes(file.type)
      const isVideoByExtension = allowedExtensions.includes(fileExtension)
      const isVideo = isVideoByType || isVideoByExtension
      
      const fileSizeMB = file.size / 1024 / 1024
      const maxSizeMB = 500 // 修改为 500MB 限制
      const isLtMaxSize = fileSizeMB < maxSizeMB

      if (!isVideo) {
        ElMessage.error('只能上传视频文件！支持格式：MP4、AVI、MOV、WMV、FLV、WEBM、MKV、3GP')
        return false
      }
      
      if (!isLtMaxSize) {
        ElMessage.error(`视频文件过大！当前文件大小：${fileSizeMB.toFixed(1)}MB，最大支持：${maxSizeMB}MB`)
        return false
      }
      
      return true
    }

    // 删除教程视频
    const handleRemoveTutorialVideo = async () => {
      if (form.videoUrl) {
        try {
          await deleteVideo(form.videoUrl)
          form.videoUrl = ''
          form.videoFilename = ''
          ElMessage.success('视频删除成功')
        } catch (error) {
          console.error('删除失败:', error)
          ElMessage.warning('视频删除失败，但已从表单中移除')
          form.videoUrl = ''
          form.videoFilename = ''
        }
      }
    }

    // 获取视频URL
    const getVideoUrl = (url) => {
      if (!url) return ''
      // 如果是完整URL，直接返回
      if (url.startsWith('http')) {
        return url
      }
      // 如果是前端静态文件路径，直接返回
      if (url.startsWith('/videos/')) {
        return url
      }
      // 如果是上传文件路径，添加后端服务器前缀
      if (url.startsWith('/uploads/')) {
        return `http://localhost:8080${url}`
      }
      // 其他情况，添加后端服务器前缀
      return `http://localhost:8080${url}`
    }

    // 获取图片URL
    const getImageUrl = (url) => {
      if (!url) return ''
      // 如果是完整URL，直接返回
      if (url.startsWith('http')) {
        return url
      }
      // 如果是前端静态文件路径，直接返回
      if (url.startsWith('/images/')) {
        return url
      }
      // 如果是上传文件路径，添加后端服务器前缀
      if (url.startsWith('/uploads/')) {
        return `http://localhost:8080${url}`
      }
      // 其他情况，添加后端服务器前缀
      return `http://localhost:8080${url}`
    }

    // 获取状态类型
    const getStatusType = (status) => {
      switch (status) {
        case 0: return 'info'    // 草稿
        case 1: return 'success' // 已发布
        case 2: return 'danger'  // 已下架
        default: return 'info'
      }
    }

    // 获取分类类型
    const getCategoryType = (category) => {
      const types = {
        1: 'success',  // 基础入门
        2: 'primary',  // 进阶技法
        3: 'warning'   // 高级创作
      }
      return types[category] || ''
    }

    // 获取难度类型
    const getDifficultyType = (difficulty) => {
      const types = {
        1: 'success',  // 初级
        2: 'warning',  // 中级
        3: 'danger'    // 高级
      }
      return types[difficulty] || ''
    }

    // 选择变更处理
    const handleSelectionChange = (selection) => {
      selectedTutorials.value = selection
    }

    // 状态变更处理
    const handleStatusChange = async (row) => {
      try {
        const response = await updateTutorial({
          ...row,
          status: row.status
        })
        if (response.code === 200) {
          ElMessage.success(`${row.status === 1 ? '发布' : '取消发布'}成功`)
          fetchTutorials()
        } else {
          throw new Error(response.message || '状态更新失败')
        }
      } catch (error) {
        console.error('状态更新失败:', error)
        ElMessage.error(error.message || '状态更新失败')
        // 回滚状态
        row.status = row.status === 1 ? 0 : 1
      }
    }

    // 批量删除处理
    const handleBatchDelete = async () => {
      const selectedCount = selectedTutorials.value.length
      if (selectedCount === 0) {
        ElMessage.warning('请先选择要删除的教程')
        return
      }

      try {
        const selectedTitles = selectedTutorials.value.slice(0, 3).map(item => item.title).join('、')
        const titleDisplay = selectedCount > 3 ? `${selectedTitles} 等` : selectedTitles

        await ElMessageBox.confirm(
          `确定删除选中的 ${selectedCount} 个教程吗？\n\n包括：${titleDisplay}\n\n删除后将无法恢复，请谨慎操作！`,
          '批量删除确认',
          {
            type: 'warning',
            dangerouslyUseHTMLString: false,
            confirmButtonText: `确认删除 ${selectedCount} 个`,
            cancelButtonText: '取消',
            confirmButtonClass: 'el-button--danger'
          }
        )

        loading.value = true
        // 这里需要实现批量删除API，暂时使用单个删除
        for (const tutorial of selectedTutorials.value) {
          await deleteTutorialApi(tutorial.id)
        }

        ElMessage.success(`批量删除成功，共删除 ${selectedCount} 个教程`)
        selectedTutorials.value = []
        fetchTutorials()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          const errorMessage = error?.response?.data?.message || error?.message || '批量删除失败，请稍后重试'
          ElMessage.error(errorMessage)
        }
      } finally {
        loading.value = false
      }
    }

    // 分页处理
    const handleSizeChange = (val) => {
      pagination.size = val
      pagination.page = 1
      fetchTutorials()
    }

    const handleCurrentChange = (val) => {
      pagination.page = val
      fetchTutorials()
    }

    // 组件挂载时获取数据
    onMounted(() => {
      fetchTutorials()
    })
    
    return {
      // 数据状态
      loading,
      saving,
      dialogVisible,
      dialogTitle,
      formRef,
      searchForm,
      tutorials,
      selectedTutorials,
      stats,
      pagination,
      form,
      rules,

      // 查看弹窗
      viewDialogVisible,
      viewData,

      // 步骤管理
      stepsDialogVisible,
      stepsLoading,
      currentTutorialForSteps,
      steps,
      stepDialogVisible,
      stepDialogTitle,
      stepSaving,
      stepFormRef,
      stepForm,
      stepRules,

      // 方法
      fetchTutorials,
      loadStats,
      searchTutorials,
      resetSearch,
      quickFilter,
      refreshData,
      openTutorialForm,
      editTutorial,
      saveTutorial,
      deleteTutorial,
      viewTutorial,
      manageSteps,
      addStep,
      editStep,
      saveStep,
      deleteStep,
      handleImageUpload,
      beforeCoverUpload,
      handleRemoveCoverImage,
      handleStepImageUpload,
      handleRemoveStepImage,
      handleStepImageSuccess,
      beforeStepImageUpload,
      handleStepVideoUpload,
      beforeStepVideoUpload,
      handleRemoveStepVideo,
      handleTutorialVideoUpload,
      beforeTutorialVideoUpload,
      handleRemoveTutorialVideo,
      getVideoUrl,
      getImageUrl,
      getStatusType,
      getCategoryType,
      getDifficultyType,
      handleSelectionChange,
      handleStatusChange,
      handleBatchDelete,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.tutorial-management {
  padding: 20px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 6px;
  padding: 20px;
  display: flex;
  align-items: center;
  border: 1px solid #e4e7ed;
}

.stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
  margin-right: 16px;
}

.stat-icon.tutorial { background-color: #409eff; }
.stat-icon.published { background-color: #67c23a; }
.stat-icon.draft { background-color: #e6a23c; }
.stat-icon.steps { background-color: #909399; }

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 13px;
  color: #606266;
}

/* 快速筛选区域 */
.quick-filter-section {
  background: white;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
}

.filter-tabs {
  display: flex;
  gap: 12px;
  align-items: center;
}

.toolbar {
  background: white;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
  border: 1px solid #e4e7ed;
}

.search-section {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  align-items: center;
}

.search-section .el-input {
  width: 200px;
}

.search-section .el-select {
  width: 120px;
}

.action-section {
  display: flex;
  gap: 8px;
}

.table-container {
  background: white;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
}

.cover-image {
  width: 60px;
  height: 40px;
  border-radius: 4px;
}

.steps-count, .view-count {
  color: #606266;
  font-weight: normal;
}

/* 分页容器 */
.pagination-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 16px 20px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
}

.custom-pagination {
  justify-content: flex-end;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
  flex-wrap: nowrap;
}

.action-buttons .el-button {
  margin: 0;
  min-width: 50px;
  padding: 5px 8px;
  font-size: 12px;
}

/* 文件上传样式 */
.upload-container {
  width: 100%;
  text-align: left;
}

.cover-uploader {
  display: inline-block;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.cover-uploader:hover {
  border-color: #409eff;
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 118px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
}

.cover-image {
  width: 178px;
  height: 118px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
  line-height: 1.4;
}

.image-actions {
  margin-top: 8px;
}

/* 视频上传样式 - 与封面上传保持一致 */
.video-uploader {
  display: inline-block;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.video-uploader:hover {
  border-color: #409eff;
}

/* 视频上传占位区域 - 与封面上传相同尺寸 */
.video-upload-placeholder {
  width: 178px;
  height: 118px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
}

.video-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

/* 视频预览容器 */
.video-preview-container {
  position: relative;
  width: 178px;
  height: 118px;
}

.video-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
  display: block;
}

.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
  border-radius: 4px;
}

.video-preview-container:hover .video-overlay {
  opacity: 1;
}

.video-play-icon {
  font-size: 24px;
  color: white;
  margin-bottom: 4px;
}

.video-overlay-text {
  color: white;
  font-size: 12px;
  text-align: center;
}

.video-actions {
  margin-top: 10px;
  text-align: center;
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: center;
}

.video-filename {
  font-size: 12px;
  color: #606266;
  padding: 4px 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  max-width: 100%;
  word-break: break-all;
  text-align: center;
}

.dialog-footer {
  text-align: center;
}

/* 查看弹窗样式 */
.view-content {
  max-height: 600px;
  overflow-y: auto;
}

.section {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.section:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.section-title {
  margin: 0 0 16px 0;
  padding-left: 8px;
  border-left: 4px solid #409eff;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  text-align: left;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.info-item label {
  font-weight: 600;
  color: #606266;
  min-width: 80px;
  flex-shrink: 0;
}

.info-item span,
.info-item p {
  color: #303133;
  margin: 0;
  word-break: break-word;
}

.cover-preview {
  text-align: center;
}

.preview-image {
  max-width: 300px;
  max-height: 200px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.content-info .info-item {
  flex-direction: column;
  align-items: flex-start;
}

.content-html {
  line-height: 1.6;
  color: #303133;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.stat-item {
  background-color: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

/* 步骤管理样式 */
.steps-management {
  min-height: 400px;
}

.steps-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.steps-header h4 {
  margin: 0;
  color: #303133;
  font-size: 18px;
}

.step-image {
  width: 60px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
}

/* 步骤图片上传 */
.step-uploader .step-upload-image {
  width: 100px;
  height: 60px;
  display: block;
  object-fit: cover;
  border-radius: 4px;
}

.step-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 100px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.step-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.step-uploader-icon {
  font-size: 20px;
  color: #8c939d;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }

  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }

  .search-section {
    justify-content: center;
  }

  .action-section {
    justify-content: center;
  }

  .pagination-wrapper {
    flex-direction: column;
    gap: 12px;
    padding: 12px;
  }

  .pagination-info {
    text-align: center;
    font-size: 13px;
  }

  .custom-pagination {
    justify-content: center;
  }

  .action-buttons {
    flex-direction: column;
    gap: 6px;
  }

  .action-buttons .el-button {
    min-width: 50px;
    font-size: 12px;
    padding: 4px 8px;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }

  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>